package data

import (
	"UserApp/conf"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/wire"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
)

var ProviderSet = wire.NewSet(ProviderData, ProviderDB, ProviderUserRepo)

type Data struct {
	db *gorm.DB
}

func ProviderDB(c conf.Config) *gorm.DB {
	addr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=%t",
		c.Ps.User, c.Ps.Password, c.Ps.Host, c.Ps.Port, c.Ps.Schema, c.Opts.Charset,c.Opts.ParseTime)
	db, err := gorm.Open(mysql.Open(addr), &gorm.Config{})
	if err != nil {
		log.Fatalf("failed opening connection to mysql: %v", err)
	}

	if err := db.AutoMigrate(&User{}); err != nil {
		log.Fatal(err)
	}
	return db
}

func ProviderData(db *gorm.DB) *Data {
	return &Data{db: db}
}